package com.linln.agent.message;

import java.math.BigDecimal;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.linln.modules.member.domain.*;
import com.linln.modules.message.domain.MessageMemberLog;
import com.linln.modules.message.domain.MessageRefund;
import com.linln.modules.message.repository.MessageRefundRepository;
import com.linln.modules.message.service.MessageMemberLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.linln.common.constant.AdminConst;
import com.linln.common.constant.NoticeTypeConst;
import com.linln.common.constant.UrlConst;
import com.linln.common.utils.DateUtils;
import com.linln.common.utils.MoneyUtils;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.ToolUtil;
import com.linln.common.vo.ResultVo;
import com.linln.modules.member.service.AreaCountService;
import com.linln.modules.member.service.MemberAgentService;
import com.linln.modules.member.service.MemberInfoService;
import com.linln.modules.member.service.MemberOrderService;
import com.linln.modules.member.service.MemberRefundService;
import com.linln.modules.message.domain.MessageInfo;
import com.linln.modules.message.domain.MessageType;
import com.linln.modules.message.repository.MessageInfoRepository;
import com.linln.modules.message.service.MessageInfoService;
import com.linln.modules.message.service.MessageTypeService;

/**
 * @author hct
 * @date 2019/09/12
 */
@Controller
@RequestMapping("agent/message")
public class AgentMessageController {

    @Autowired
    private MessageInfoService baseinfoService;
     @Autowired
	private AreaCountService areaCountService;
     @Autowired
     private MemberAgentService agentService;
     @Autowired
     private MemberInfoService memberService;
    @Autowired
    private MessageInfoRepository messageInfoRepository;
    @Autowired
    private MessageTypeService typeService;

     @Autowired
     private WxPayService wxPayService;
     @Autowired
     private MemberRefundService refundService;
     @Autowired
     private MessageMemberLogService messageMemberLogServiceImpl;
     @Autowired
     private MessageRefundRepository messageRefundRepository;
     @Autowired
     private MemberInfoService memberInfoService;
     
     private static final String REFUND_SUCCESS = "SUCCESS";
    private static final String REFUND_FAIL = "FAIL";


    @Autowired
     private MemberOrderService orderService;
    /**
     * 所有信息列表页面
     */
    @GetMapping("/index")
    public String index(Model model, MessageInfo baseinfo,Long message_type2,HttpServletRequest request) {
        // 创建匹配器，进行动态查询匹配

        ExampleMatcher matchertype = ExampleMatcher.matching();
        // 获取部门列表
        MessageType type=new MessageType();
        Example<MessageType> exampleType = Example.of(type, matchertype);
        Sort sort = new Sort(Sort.Direction.ASC, "num");
        List<MessageType> typealllist = typeService.getListByExample(exampleType, sort);
        List<MessageType> typelist=new ArrayList<MessageType>();
        for(MessageType messageType:typealllist) {
            if(messageType.getPid()!=null && messageType.getPid().longValue()>0) {
                typelist.add(messageType);
            }
        }
        // 创建匹配器，进行动态查询匹配
        if(message_type2!=null && message_type2.longValue()>0) {
            MessageType typenew=new MessageType();
            typenew.setId(message_type2);
            baseinfo.setTypetwo(typenew);
        }

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("title", match -> match.contains());
        baseinfo.setMessageStatus(baseinfo.getMessageStatus());
       // MemberInfo agent=(MemberInfo)request.getSession().getAttribute(AdminConst.AGENT_ROLE_NAME);
        MemberAgent agent=(MemberAgent)request.getSession().getAttribute(AdminConst.AGENT_AREA_NAME); 
        baseinfo.setMessageStatus(1);
        baseinfo.setArea(agent.getArea());        
        // 获取数据列表
        Example<MessageInfo> example = Example.of(baseinfo, matcher);
        Page<MessageInfo> list = baseinfoService.getPageList(example);
        // 封装数据
        model.addAttribute("typelist", typelist);
        model.addAttribute("message_type2", message_type2);
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/agent/message/index";
    }
    
    /**
     * 所有置顶列表页面
     */
    @GetMapping("/topindex")
    public String topindex(Model model, MessageInfo baseinfo,HttpServletRequest request) {

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("title", match -> match.contains());
        baseinfo.setMessageStatus(1);
        baseinfo.setIstop(1);
        MemberAgent agent=(MemberAgent)request.getSession().getAttribute(AdminConst.AGENT_AREA_NAME); 
        
       // MemberInfo agent=(MemberInfo)request.getSession().getAttribute(AdminConst.AGENT_ROLE_NAME);
        baseinfo.setArea(agent.getArea());        
        // 获取数据列表
        Example<MessageInfo> example = Example.of(baseinfo, matcher);
        Page<MessageInfo> list = baseinfoService.getPageList(example);
        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        model.addAttribute("payStatus",baseinfo.getPayStatus());
        return "/agent/message/topindex";
    }
    
    /**
     * 待审核列表页面
     */
    @GetMapping("/shenheindex")
    public String shenheindex(Model model, MessageInfo baseinfo,HttpServletRequest request) {

    	// 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("title", match -> match.contains());
        baseinfo.setMessageStatus(0);
        //baseinfo.setIstop(1);   
        //baseinfo.setPayStatus(1);
        //MemberInfo agent=(MemberInfo)request.getSession().getAttribute(AdminConst.AGENT_ROLE_NAME);
        MemberAgent agent=(MemberAgent)request.getSession().getAttribute(AdminConst.AGENT_AREA_NAME); 
        
        baseinfo.setArea(agent.getArea());        
        // 获取数据列表
        Example<MessageInfo> example = Example.of(baseinfo, matcher);
        Page<MessageInfo> list = baseinfoService.getPageList(example);
        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/agent/message/shenheindex";
    }
    /**
     * 审核
     * @param model
     * @param id
     *   0待审核 1同意 2拒绝
     * @param request
     * @return
     */
    @GetMapping("/toshenhe/{id}")
     public String toshenhe(Model model, @PathVariable Long id,HttpServletRequest request) {
    	 model.addAttribute("id", id);
    	 return "/agent/message/toshenhe";
    }
    
 /*   *//**
     * 审核
     * @param model
     *
     *   0待审核 1同意 2拒绝
     *
     * @return
     *//*
    @PostMapping("/shenheMessage")
    @ResponseBody
    public ResultVo shenheMessage(Model model, Long id ,Integer messageStatus,HttpServletRequest request) {
    	MessageInfo message=baseinfoService.getById(id);
    	//MemberInfo agent=(MemberInfo)request.getSession().getAttribute(AdminConst.AGENT_ROLE_NAME);
        MemberAgent agent=(MemberAgent)request.getSession().getAttribute(AdminConst.AGENT_AREA_NAME); 
         
    	if(baseinfoService.updateMessageStatus(messageStatus, id)) {
    		
    		if(messageStatus.intValue()==1) {
            	//同意的时候将钱增加到代理商的余额中
            	MemberAgent agentnew=agentService.getById(agent.getId());
            	//代理商拿一个比例的折扣，其他的归属公司
            	Double curagentmoney=MoneyUtils.mul(message.getFee(),0.9);
            	agentnew.setAllmoney(MoneyUtils.add(agentnew.getAllmoney(), curagentmoney));
            	agentnew.setCurmoney(MoneyUtils.add(agentnew.getCurmoney(),curagentmoney));
            	agentService.save(agentnew);
            	MemberInfo memberinfo=memberService.getById(agent.getId());
            	memberinfo.setAllmoney(MoneyUtils.add(memberinfo.getAllmoney(), curagentmoney));
            	memberinfo.setMoney(MoneyUtils.add(memberinfo.getMoney(), curagentmoney));
            	memberService.save(memberinfo);
            }else if(messageStatus.intValue()==2) {
            	if(message.getIstop()==1) {
            		//拒绝的时候将费用退回给客户 申请退款
                   WxPayRefundRequest refundInfo = WxPayRefundRequest.newBuilder()
                           //订单号
                           .outTradeNo(message.getOrderId())
                           //退款订单号
                           .outRefundNo(ToolUtil.getRandomString(16)) 
                           //金额
                           .totalFee(yuanToFee(new BigDecimal(message.getFee())))
                           //退款金额
                           .refundFee(yuanToFee(new BigDecimal(message.getFee())))
                           //todo 回调地址
                           .notifyUrl(UrlConst.REFUNDNOTICEURL)
                           .build();
                   WxPayRefundResult wxPayRefundResult;
                   try {
                       wxPayRefundResult = wxPayService.refund(refundInfo);
                       //判断退款信息是否正确
                       if (REFUND_SUCCESS.equals(wxPayRefundResult.getReturnCode())
                               && REFUND_SUCCESS.equals(wxPayRefundResult.getResultCode())) {
                   		     saveRefund( message,agent.getId());

                        }
                   } catch (WxPayException e) {
                   	return ResultVoUtil.error("异常");
                   }
            	}else {
            		saveRefund( message,agent.getId());
            	}
            	
            }	
    		
         return ResultVoUtil.success("审核成功");

    	}else {
    		return ResultVoUtil.error("审核失败");
    	}
    	
    }*/

    @RequestMapping("/refundRedirect/{id}")
    public String refundRedirect(@PathVariable("id") MessageInfo baseinfo,Model model){
        model.addAttribute("messageInfo",baseinfo);
        return "/agent/message/refund";
    }

    
    /**
     * 下架消息 并将钱退回去
     * @param model
     * @param id
     *   0待审核 1同意 2拒绝
     * @param request
     * @return
     */
    @RequestMapping("/refundMessage")
    @ResponseBody
    public ResultVo refundMessage(Model model, Long id,String refundContent,HttpServletRequest request) {
    	MessageInfo message=baseinfoService.getById(id);
    	//MemberInfo agent=(MemberInfo)request.getSession().getAttribute(AdminConst.AGENT_ROLE_NAME);
        MemberAgent agent=(MemberAgent)request.getSession().getAttribute(AdminConst.AGENT_AREA_NAME);          
    	if(baseinfoService.updateMessageStatus(2, id)) {
            Long agentId = message.getAgentId();
            MessageRefund messageRefund=new MessageRefund();
            messageRefund.setMessageId(id);
            messageRefund.setMemberId(message.getMember().getId());
            messageRefund.setCreateDate(new Date());
            messageRefund.setUpdateDate(new Date());
            messageRefund.setContent(refundContent);
            messageRefund.setStatus(0);
            messageRefundRepository.save(messageRefund);
            MemberOrder memberOrder=orderService.findByOrderCode(message.getOrderId());
            	if(message.getIstop()==1 &&memberOrder.getMoney().doubleValue()>0) {//置顶的退款 其他的拒绝掉
            		//拒绝的时候将费用退回给客户 申请退款
                   WxPayRefundRequest refundInfo = WxPayRefundRequest.newBuilder()
                           //订单号
                           .outTradeNo(message.getOrderId())
                           //退款订单号
                           .outRefundNo(ToolUtil.getRandomString(16)) 
                           //金额
                           .totalFee(yuanToFee(new BigDecimal(memberOrder.getMoney())))
                           //退款金额
                           .refundFee(yuanToFee(new BigDecimal(memberOrder.getMoney())))
                          
                           //todo 回调地址
                           .notifyUrl(UrlConst.REFUNDNOTICEURL)
                           .build();
                   WxPayRefundResult wxPayRefundResult;
                   try {
                       wxPayRefundResult = wxPayService.refund(refundInfo);
                       //判断退款信息是否正确
                       if (REFUND_SUCCESS.equals(wxPayRefundResult.getReturnCode())
                               && REFUND_SUCCESS.equals(wxPayRefundResult.getResultCode())) {
                   		     saveRefund( message,memberOrder,agent.getId());
                   		  MemberAgent agentnew=agentService.getById(agent.getId());
                       	  agentnew.setAllmoney(MoneyUtils.sub(agentnew.getAllmoney(), memberOrder.getMoney()));
                      	  agentnew.setCurmoney(MoneyUtils.sub(agentnew.getCurmoney(),memberOrder.getMoney()));
                      	  agentService.save(agentnew);
                		  orderService.updateRefundStatus(message.getOrderId());
                        }else if(REFUND_FAIL.equals(wxPayRefundResult.getReturnCode())){
                           return ResultVoUtil.success("下架成功,但退款失败:"+wxPayRefundResult.getReturnMsg());
                       }
                   } catch (WxPayException e) {
                   	System.out.println("没有需要退款的情况"); 
                   }
                   return ResultVoUtil.success("下架成功");
                   
            	}else {
            		saveRefund( message,memberOrder,agent.getId());
            	}
            	
            	
    		
         return ResultVoUtil.success("下架成功");

    	}else {
    		return ResultVoUtil.error("下架失败");
    	}
    	
    }
    
    
    public void saveRefund(MessageInfo message,MemberOrder order,Long agentId) {
    	MemberRefund refund=new MemberRefund();
       	refund.setAgentId(agentId);
       	refund.setArea(message.getArea());
       	refund.setMoney(0d);
       	refund.setRefundmoney(0d);

       	refund.setContent("下架普通信息");
       	if(message.getIstop().intValue()==1) {
       		refund.setContent("拒绝用户置顶信息");
           	refund.setMoney(order.getMoney());
           	refund.setRefundmoney(order.getMoney());
       	}
       	refund.setOrderCode(message.getOrderId());
       	refund.setRefundStatus(0);
       	refund.setType(NoticeTypeConst.MESSAGE);
       	refund.setTypeId(message.getId());
       	refundService.save(refund);
    }
    
    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
     public String toDetail(@PathVariable("id") MessageInfo baseinfo, Model model) {
        List<MessageMemberLog> messageMemberLogs = messageMemberLogServiceImpl.getMemberListByMessage(baseinfo.getId());
        List<MemberInfo> members=new ArrayList<>();
        Set<Long> memeberIds=new HashSet<>();
        for ( MessageMemberLog messageMemberLog : messageMemberLogs
        ) {
            memeberIds.add(messageMemberLog.getMember().getId());
        }
        for (Long id : memeberIds
        ) {
            MemberInfo memberInfo = memberInfoService.getById(id);
            members.add(memberInfo);
        }
        baseinfo.setMemberInfos(members);
        model.addAttribute("baseinfo",baseinfo);
        return "/agent/message/detail";
    }

    @GetMapping("/getAudienceMessage/{id}")
    public String getAudienceMessage(@PathVariable("id") Long id,Model model){
        MemberInfo memberInfo = memberInfoService.getById(id);
        model.addAttribute("memberInfo",memberInfo);
        return "/agent/message/userDetail";
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/edit/{id}")
    public String selectEdit(@PathVariable("id") MessageInfo baseinfo, Model model) {
        model.addAttribute("baseinfo",baseinfo);
        return "/agent/message/edit";
    }
    /**
     * 编辑
     */
    @PostMapping("/editMessageInfo")
    @ResponseBody
    public ResultVo editMessageInfo(Long id, String details, String pushPhone,String title, String logo, String nineImgs, String startTime,Integer readnum, HttpServletRequest request){
    	 if(!StringUtils.isEmpty(nineImgs)){
             String tmp=nineImgs.substring(nineImgs.length()-1,nineImgs.length());
             if(",".equals(tmp)){
                 nineImgs=nineImgs.substring(0,nineImgs.length()-1);
             }
         }
    	MessageInfo baseinfo=messageInfoRepository.getOne(id);
    	baseinfo.setDetails(details);
    	baseinfo.setTitle(title);
    	baseinfo.setLogo(logo);
    	baseinfo.setImgs(nineImgs);
        baseinfo.setPushPhone(pushPhone);
    	baseinfo.setStartTime(DateUtils.strToDate(startTime,"yyyy-MM-dd hh:mm:ss")); 
    	baseinfo.setReadnum(readnum);
    	messageInfoRepository.saveAndFlush(baseinfo);
    	//Integer integerdetails = messageInfoRepository.updateMessageInfodetails(id, details);
       // Integer integertitle = messageInfoRepository.updateMessageInfotitle(id, title);
       
       // messageInfoRepository.updateMessageInfoImgs(id,nineImgs);
       // messageInfoRepository.updateMessageInfoLogo(id,logo);
      //  messageInfoRepository.updateMessageInfoStartTime(id,DateUtils.strToDate(startTime,"yyyy-MM-dd hh:mm:ss"));
        System.out.println(id+"----"+details);
        ResultVo success = ResultVoUtil.success("修改成功");
        return success;
    }


    /**
	* 获取商户设置基础信息

	* @return
	*/
	@RequestMapping(value = "areacount",method= {RequestMethod.POST,RequestMethod.GET})
 	public String messageset(HttpServletRequest request ) {
	
 		MemberInfo agent=(MemberInfo)request.getSession().getAttribute(AdminConst.AGENT_ROLE_NAME);
         
 	    AreaCount areacount = areaCountService.findByArea(agent.getArea());
       
 		 
	    return "/agent/message/areacount/index";
	
	}
	
	/**
     * 1 块钱转为 100 分
     * 元转分
     *
     * @param bigDecimal 钱数目
     * @return 分
     */
    private int yuanToFee(BigDecimal bigDecimal) {
        return bigDecimal.multiply(new BigDecimal(100)).intValue();
    }

    /**
     * 时间
     *
     * @return 时间戳
     */
    private String createTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}